package com.example.multilanguagedemo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.TextView;

import androidx.annotation.Nullable;

import java.util.Locale;
import java.util.Stack;

public class MainActivity extends BaseActivity {
    private TextView mTvChangeToChinese;
    private TextView mTvChangeToEnglish;
    private TextView mTvChangeToRussian;
    private TextView mTvToSecond;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTvChangeToChinese = (TextView) findViewById(R.id.tv_change_to_chinese);
        mTvChangeToEnglish = (TextView) findViewById(R.id.tv_change_to_english);
        mTvChangeToRussian = (TextView) findViewById(R.id.tv_change_to_russian);
        mTvToSecond = (TextView) findViewById(R.id.tv_to_second);
        mTvChangeToChinese.setOnClickListener(v -> changeAllActivitysLanguage(Locale.CHINESE));
        mTvChangeToEnglish.setOnClickListener(v -> changeAllActivitysLanguage(Locale.US));
        mTvChangeToRussian.setOnClickListener(v -> changeAllActivitysLanguage(Locale.FRANCE));
        mTvToSecond.setOnClickListener(v -> startActivity(new Intent(this, SecondActivity.class)));
    }

    private void changeAllActivitysLanguage(Locale locale) {
        Stack<Activity> allActivityStacks = AppManager.getInstance().getAllActivityStacks();
        shiftLanguage(locale, this);
    }

    /**
     * 这个方法是为了让全部的activity都修改语言
     *
     * @param locale
     * @param activity
     * @param context
     */
    public static void shiftLanguage(Locale locale, Activity activity, Context context) {
        Resources resources = context.getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        config.locale = locale;
        resources.updateConfiguration(config, dm);
        if (!(activity instanceof MainActivity)) {
            activity.recreate();
        }

    }

    /**
     * 这个方法虽然更新了资源但是只能以后的界面生效，之前没有finish的页面还是保留原来的语言
     *
     * @param locale
     * @param context
     */
    public static void shiftLanguage(Locale locale, Context context) {
        Resources resources = context.getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        config.locale = locale;
        resources.updateConfiguration(config, dm);

    }


}
